package com.hyacinth.cloudnote.modules.note.converter;

import com.hyacinth.cloudnote.common.converter.AbstractConverter;
import com.hyacinth.cloudnote.common.enums.UserStatus;
import com.hyacinth.cloudnote.common.exception.ExceptionHolder;
import com.hyacinth.cloudnote.modules.note.dto.UserDTO;
import com.hyacinth.cloudnote.modules.note.model.User;
import com.hyacinth.cloudnote.modules.note.repository.UserRepository;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.hyacinth.cloudnote.modules.common.errorcode.NoteErrorCode.E1000000001;

/**
 * User实体与DTO之间接口数据转换实现
 * @author zhangfb
 */
@Component
public class UserConverter extends AbstractConverter<User, UserDTO> {
    @Autowired
    private UserRepository userRepository;


    @Override
    public User toModel(@NonNull final UserDTO dto) {
        if (dto.isNew()) {
            return constructModel(dto);
        } else {
            return updateModel(dto);
        }
    }

    @Override
    public UserDTO toDTO(@NonNull final User model) {
        final UserDTO dto = new UserDTO();

        dto.setId(model.getId());
        dto.setMobile(model.getMobile());
        dto.setUsername(model.getUsername());
        dto.setEmail(model.getEmail());
        dto.setRealName(model.getRealName());
        dto.setStatus(model.getStatus());
        dto.setPortrait(model.getPortrait());

        this.convertCommonToDTO(model, dto);

        return dto;
    }

    /**
     * 构建新Model
     */
    private User constructModel(final UserDTO dto) {
        final User model = new User();
        model.setStatus(UserStatus.ACTIVE);
        this.dtoToModel(dto, model);
        return model;
    }

     /**
      * 更新Model
      */
    private User updateModel(final UserDTO dto) {
        final User model = this.userRepository.findById(dto.getId())
                        .orElseThrow(() -> ExceptionHolder.serviceException(E1000000001, "用户-" + dto.getId()));

        this.dtoToModel(dto, model);
        return model;
    }

    private void dtoToModel(final UserDTO dto, final User model) {
        model.setMobile(dto.getMobile());
        model.setUsername(dto.getUsername());
        model.setEmail(dto.getEmail());
        model.setRealName(dto.getRealName());
        model.setPortrait(dto.getPortrait());

    }
}
